package com.ruoyi.quartz.task;


import com.snowRemovingUser.domain.MDevice;
import com.snowRemovingUser.domain.MDeviceAttribute;
import com.snowRemovingUser.mapper.MDeviceAttributeMapper;
import com.snowRemovingUser.mapper.MDeviceMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 定时检查设备总状态
 */
@Component("deviceStateTask")
public class DeviceStateTask {

    /** log */
    protected Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private MDeviceMapper deviceMapper;

    @Autowired
    private MDeviceAttributeMapper mDeviceAttributeMapper;


    public void deviceState(){


        try {

            MDeviceAttribute mDeviceAttribute = new MDeviceAttribute();
            MDevice mDevice = new MDevice();

            List<MDeviceAttribute> mDeviceAttributes = mDeviceAttributeMapper.selectMDeviceAttributeList(mDeviceAttribute);
            List<MDevice> deviceList = deviceMapper.selectMDeviceList(mDevice);

            //将 mDeviceAttributes 将SerialNumber 相同的放入一个集合 用map封装
            Map<String, List<MDeviceAttribute>> deviceAttributeListBySerialNumber = mDeviceAttributes.stream().collect(Collectors.groupingBy(MDeviceAttribute::getSerialNumber));

            //将 codeNameList 用map封装
            Map<String, MDevice> deviceListBySerialNumber = deviceList.stream().collect(Collectors.toMap(MDevice::getSerialNumber, Function.identity()));

            Set<String> keySet = deviceAttributeListBySerialNumber.keySet();

            for (String s : keySet) {

                List<MDeviceAttribute> deviceAttributeList = deviceAttributeListBySerialNumber.get(s);
                for (MDeviceAttribute deviceAttribute : deviceAttributeList) {

                    MDevice device = deviceListBySerialNumber.get(deviceAttribute.getSerialNumber());

                    //首先把总状态设置为在线 再根据设备属性判断它是否离线
                    device.setOverallStatus(0);
                    deviceMapper.updateMDevice(device);
                    //属性状态中有一个为离线(1) 总状态也设为离线(1)(前提是总状态不等于停用(2))
                    if (deviceAttribute.getAttributeStatus()==1 ){

                        device.setOverallStatus(1);
                        deviceMapper.updateMDevice(device);
                        break;
                    }else if (deviceAttribute.getAttributeStatus()==2 && device.getOverallStatus()!=1){

                        device.setOverallStatus(2);
                        deviceMapper.updateMDevice(device);
                        break;
                    }
                }
            }
            logger.info("设备总状态更新完成");

        } catch (Exception e) {

            logger.error("设备总状态更新失败");
            logger.error(e.getMessage());
        }
    }





}
